package com.java1412.web.service.impl;

import com.java1412.common.dto.UserDto;
import com.java1412.common.entity.User;
import com.java1412.common.utils.PageUtil;
import com.java1412.common.utils.R;
import com.java1412.common.utils.ResponseEnum;
import com.java1412.web.mapper.UserMapper;
import com.java1412.web.service.UserService;
import com.java1412.web.utils.JWTUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author java1412
 * @since 2025-05-16 14:00
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JWTUtil jwtUtil;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public R selectById(Integer id) {
        User user = userMapper.selectById(id);
        user.setLoginPassword(null);
        return user != null ? R.r(ResponseEnum.USER_FIND_ID_SUCCESS, user) : R.r(ResponseEnum.USER_FIND_ID_FAILURE);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public R apiLogin(UserDto userDto) {
//        USER_LOGIN_FAILURE_1(1004, "用户登录失败,验证码失效"),
//        USER_LOGIN_FAILURE_2(1005, "用户登录失败,手机号不匹配"),
//        USER_LOGIN_FAILURE_3(1006, "用户登录失败,手机号和验证码不匹配"),
//        USER_LOGIN_FAILURE_4(1007, "用户登录失败,手机号和密码不匹配"),
//        USER_LOGIN_FAILURE_5(1008, "用户登录失败,角色不匹配"),
        R r = null;
        String redisPhoneAndCode = stringRedisTemplate.opsForValue().get(userDto.getUuid());
        if (null == redisPhoneAndCode) {
            // 验证码过期
            r = R.r(ResponseEnum.USER_LOGIN_FAILURE_1);
        } else {
            String redisPhone = redisPhoneAndCode.split("-")[0];
            String redisCode = redisPhoneAndCode.split("-")[1];
            if (!redisPhone.equals(userDto.getPhone())) {
                r = R.r(ResponseEnum.USER_LOGIN_FAILURE_2);
            } else if (!redisCode.equals(userDto.getCode())) {
                r = R.r(ResponseEnum.USER_LOGIN_FAILURE_3);
            } else {
                User loginUser = userMapper.findByPhone(userDto);
                if (null == loginUser) {
                    r = R.r(ResponseEnum.USER_LOGIN_FAILURE_2);
                } else if (!loginUser.getLoginPassword().equals(userDto.getLoginPassword())) {
                    r = R.r(ResponseEnum.USER_LOGIN_FAILURE_4);
                } else if (loginUser.getRole().intValue() != 1) {
                    r = R.r(ResponseEnum.USER_LOGIN_FAILURE_5);
                } else {
                    // 登录成功
                    // 修改最后登录成功的时间是当前日期和时间
                    loginUser.setLastLoginTime(new Date());
                    // 调用mapper完成更新
                    userMapper.updateLastLoginTime(loginUser);
                    loginUser.setLoginPassword(null);
                    // 登录成功后需要删除redis中的验证码
                    stringRedisTemplate.delete(userDto.getUuid());
                    r = R.r(ResponseEnum.USER_LOGIN_SUCCESS, loginUser);
                }
            }
        }
        return r;
    }

    @Override
    public R adminLogin(UserDto userDto) {
        //        USER_LOGIN_FAILURE_1(1004, "用户登录失败,验证码失效"),
//        USER_LOGIN_FAILURE_2(1005, "用户登录失败,手机号不匹配"),
//        USER_LOGIN_FAILURE_3(1006, "用户登录失败,手机号和验证码不匹配"),
//        USER_LOGIN_FAILURE_4(1007, "用户登录失败,手机号和密码不匹配"),
//        USER_LOGIN_FAILURE_5(1008, "用户登录失败,角色不匹配"),
        R r = null;
        String redisCode = stringRedisTemplate.opsForValue().get(userDto.getUuid());
        if (redisCode == null) {
            r = R.r(ResponseEnum.USER_LOGIN_FAILURE_1);
        } else if (!redisCode.equals(userDto.getCode())) {
            r = R.r(ResponseEnum.USER_LOGIN_FAILURE_3);
        } else {
            User loginUser = userMapper.findByPhone(userDto);
            if (null == loginUser) {
                r = R.r(ResponseEnum.USER_LOGIN_FAILURE_2);
            } else if (!loginUser.getLoginPassword().equals(userDto.getLoginPassword())) {
                r = R.r(ResponseEnum.USER_LOGIN_FAILURE_4);
            } else if (loginUser.getRole().intValue() != 0) {
                r = R.r(ResponseEnum.USER_LOGIN_FAILURE_5);
            } else {
                // 根据登录成功用户信息生成token
                Map<String, String> map = new HashMap<>();
                map.put("phone", userDto.getPhone());
                String token = jwtUtil.getToken(map);
                // 登录成功需要删除缓存中得code
                stringRedisTemplate.delete(userDto.getUuid());
                r = R.r(ResponseEnum.USER_LOGIN_SUCCESS, token);
            }
        }
        return r;
    }

    @Override
    public R find(UserDto userDto) {
        // 根据第几页计算从第几条开始查询
        userDto.setStartIndexNo((userDto.getCurrentPageNo() - 1) * userDto.getPageSize());
        List<User> data = userMapper.find(userDto);
        Integer totalCount = userMapper.findCount(userDto);
        // 将查询结果封装到pageUtil中
        PageUtil<User> pageUtil = new PageUtil<>();
        pageUtil.setCurrentPageNo(userDto.getCurrentPageNo());
        pageUtil.setPageSize(userDto.getPageSize());
        pageUtil.setTotalCount(totalCount);
        pageUtil.setData(data);
        return R.r(ResponseEnum.USER_FIND_ID_SUCCESS, pageUtil);
    }

    @Override
    public R add(UserDto userDto) {
        R r = null;
        // 校验验证码
        String redisPhoneAndCode = stringRedisTemplate.opsForValue().get(userDto.getUuid());
        if (redisPhoneAndCode == null) {
            r = R.r(ResponseEnum.USER_REGISTER_FAIL);
        } else {
            String redisPhone = redisPhoneAndCode.split("-")[0];
            String redisCode = redisPhoneAndCode.split("-")[1];
            if (!redisPhone.equals(userDto.getPhone())
                    || !redisCode.equals(userDto.getCode())) {
                r = R.r(ResponseEnum.USER_REGISTER_FAIL);
            } else {
                // 手机号和验证码是匹配的
                // 设置注册时间
                userDto.setAddTime(new Date());
                // 设置角色是1，普通用户
                userDto.setRole(1);
                Integer result = userMapper.add(userDto);
                if (result.intValue() > 0) {
                    // 删除验证码
                    stringRedisTemplate.delete(userDto.getUuid());
                    r = R.r(ResponseEnum.USER_REGISTER_SUCCESS);
                } else {
                    r = R.r(ResponseEnum.USER_REGISTER_FAIL);
                }
            }
        }
        return r;
    }

    @Override
    public R realNameAuthentication(UserDto userDto) {
        R r = null;
        try {
            userMapper.realNameAuthentication(userDto);
            r = R.r(ResponseEnum.USER_REAL_NAME_AUTHENTICATION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            r = R.r(ResponseEnum.USER_REAL_NAME_AUTHENTICATION_FAIL);
        }
        return r;
    }
}
